package mvcc

func GetReadView(rowId int64) *ReadView {
	if rw, ok := RowReadView.Load(rowId); ok {
		return rw.(*ReadView)
	} else {
		rw1 := &ReadView{
			List:         []IRow{},
			UpLimitId:    0,
			LowerLimitId: TrId,
		}
		RowReadView.Store(rowId, rw1)
		return rw1
	}

}

// 如果有数据变化，调用
func (rw *ReadView) CanCommit(id int64, trId int64, level int) bool {
	if level == 0 {
		return true
	}
	if trId < rw.UpLimitId {
		return false
	}
	row := find(id)
	if row.GetTrId() < trId && trId < *rw.LowerLimitId {
		return true
	}

	return false
}

// 如果存在正在rw获取事务当前版本
func (rw *ReadView) GetData(trId int64) IRow {
	for _, v := range rw.List {
		if trId == v.GetTrId() {
			return v
		}
	}
	return nil
}

func (rw *ReadView) ResetRollPtr(trId int64, ptr IRow) {
	for _, v := range rw.List {
		rowPtr := v.GetRollPtr()
		if rowPtr == nil {
			continue
		}

		if rowPtr.GetTrId() == trId {
			v.SetRollPtr(ptr)
		}
	}
}

func (rw *ReadView) RemoveList(trId int64) {
	for i, v := range rw.List {
		if v.GetTrId() == trId {
			rw.List = append(rw.List[0:i], rw.List[i+1:]...)
			break
		}
	}

}
